/**
 * Created by oneminute on 8/29/14.
 */

var util = require('util');
var winston = require('winston');
var amqp = require('amqp');

var MessageQueueLogger = function (_opts) {
    var opts = _opts || {};
    this.options = opts;

    winston.Transport.call(this, opts);

    var self = this;
    this.name = 'messagequeue';
    this.exchangeName = opts.exchangeName || "amq.rabbitmq.log";
    this.routingKey = opts.routingKey || "";
    this.publishOpts = opts.publishOpts || {};
    this.rabbitOpts = opts.rabbitOpts || {
        host: "127.0.0.1",
        port: 5672,
        login: 'guest',
        password: 'guest',
        connectionTimeout: 0,
        authMechanism: "AMQPLAIN",
        vhost: '/',
        ssl: {
            enabled: false
        }
    };

    this.localQueue = [];

    // 初始化amqp环境
    this.connection = amqp.createConnection(this.rabbitOpts);
    this.exchange = null;

    this.connection.on('error', function (_err) {
        console.error("[mq] " + _err);
    });

    this.connection.on('close', function (_err) {
        console.log('[mq] Message Queue in winston transport has bean closed.');
    });

    this.connection.on('ready', function (_err) {
        self.connection.exchange(self.exchangeName, {
            type: 'fanout',
            durable: true,
            autoDelete: false
        }, function (_exchange) {
            self.exchange = _exchange;
        });

    });
};

util.inherits(MessageQueueLogger, winston.Transport);

MessageQueueLogger.prototype.name = 'messagequeue';

winston.transports.MessageQueue = MessageQueueLogger;

MessageQueueLogger.prototype.log = function (_level, _msg, _meta, _callback) {
    var self = this;

    var output = {
        level: _level,
        message: _msg,
        meta: _meta,
        label: this.options.label,
        timestamp: this.options.timestamp()
    };

    if (self.exchange) {
        while (self.localQueue.length > 0) {
            self.exchange.publish(self.routingKey, self.localQueue.shift(), self.publishOpts);
        }

        self.exchange.publish("iwant.log", output, self.publishOpts);

        if (_callback) {
            _callback(null, true);
        }
    } else {
        self.localQueue.push(output);
    }

};

